package api

import (
	"gitee.com/gopher2011/gin"
	"strconv"
)

// 客户端分页查询请求参数的默认值
const (
	PageSize = 10
	PageNum  = 1
)

//错误码定义(根据项目要求自定义错误码)
const (
	SUCCESS       = 200
	ERROR         = 500
	InvalidParams = 400

	ErrExistTag        = 10001
	ErrNotExistTag     = 10002
	ErrNotExistArticle = 10003

	ErrAuthCheckTokenFail    = 20001
	ErrAuthCheckTokenTimeout = 20002
	ErrAuthToken             = 20003
	ErrAuth                  = 20004

	ErrExistUser = 30001

	PageNotFound = 40001
)

//MsgFlags 错误信息(匹配错误信息)
var MsgFlags = map[int]string{
	SUCCESS:                  "ok",
	ERROR:                    "fail",
	InvalidParams:            "请求参数错误",
	ErrExistTag:              "已存在该标签名称",
	ErrNotExistTag:           "该标签不存在",
	ErrNotExistArticle:       "该文章不存在",
	ErrAuthCheckTokenFail:    "Token鉴权失败",
	ErrAuthCheckTokenTimeout: "Token已超时",
	ErrAuthToken:             "Token生成失败",
	ErrAuth:                  "Token错误",
	PageNotFound:             "Page not found",
	ErrExistUser:             "用户名已存在",
}

//GetMsg 获取错误信息
func GetMsg(code int) string {
	msg, ok := MsgFlags[code]
	if ok {
		return msg
	}

	return MsgFlags[ERROR]
}

// ResponseData 数据返回结构体
type ResponseData struct {
	Code int         `json:"code" form:"code"`
	Msg  string      `json:"msg" form:"msg"`
	Data interface{} `json:"data" form:"data"`
}

// ResponseSuccess 返回成功结构体
type ResponseSuccess struct {
	Code int    `json:"code"`
	Msg  string `json:"msg" form:"msg"`
}

// ResponseFail 返回成功结构体(详情)
type ResponseFail struct {
	Code   int    `json:"code" form:"code"`
	Msg    string `json:"msg" form:"msg"`
	Detail string `json:"detail" form:"detail"`
}

// RespJSON 返回JSON数据 参数<httpCode>:http响应状态码,<resp>被返回的数据
func RespJSON(c *gin.Context, httpCode int, resp interface{}) {
	c.JSON(httpCode, resp)
}

//RespOk 返回操作成功
func RespOk(c *gin.Context, httpCode, code int) {
	resp := ResponseSuccess{
		Code: code,
		Msg:  GetMsg(code),
	}
	RespJSON(c, httpCode, resp)
}

//RespFail 返回操作失败
func RespFail(c *gin.Context, httpCode, code int, detail string) {
	resp := ResponseFail{
		Code:   code,
		Msg:    GetMsg(code),
		Detail: detail,
	}
	RespJSON(c, httpCode, resp)
}

//RespData 数据返回
func RespData(c *gin.Context, httpCode, code int, data interface{}) {
	resp := ResponseData{
		Code: code,
		Msg:  GetMsg(code),
		Data: data,
	}
	RespJSON(c, httpCode, resp)
}

// GetPage 获取每页数量，请求方法:Get 或者 Post，输入参数为: page,limit
func GetPage(c *gin.Context) (pageNum, pageSize int) {
	pageNum, _ = strconv.Atoi(c.Query("page"))
	pageSize, _ = strconv.Atoi(c.Query("limit"))
	if pageSize == 0 {
		pageSize = PageSize
	}
	if pageNum == 0 {
		pageNum = PageNum
	}
	return
}
